<script>
import { Button } from "@/components/Button";
import { msgPost } from "@/components/Post/src/msgPost";
import { Form } from "ant-design-vue";

export default {
  props: {
    showFee: {
      type: Boolean,
      default: false,
    },
    // 评论
    isPayComment: {
      required: false,
      default: false,
      type: Boolean,
    },
    // 转发
    isPayForward: {
      required: false,
      default: false,
      type: Boolean,
    },
    quotePin: {
      required: false,
      type: Object,
    },
  },
  components: {
    Button,
    Form,
    FormItem: Form.Item,
    msgPost,
  },
  computed: {
    title() {
      if (this.isPayComment) {
        if (!this.quotePin) {
          this.$message.error("param error");
        }
        return "Comment Buzz";
      }
      if (this.isPayForward) {
        if (!this.quotePin) {
          this.$message.error("param error");
        }
        return "Forward Buzz";
      }
      return "New Buzz";
    },
  },
  data() {
    return {
      selectedRate: "",
      fileInfos: [],
      feeRates: [],
      isMobile: false,
      t: null,
      sureBtnLoading: false,
      form: {},
    };
  },
  computed: {
    feeRateOptions() {
      return this.feeRates.map((rate) => ({
        label: `${rate.name} ${rate.value}`,
        value: rate.value,
      }));
    },
  },
  watch: {
    isMobile(newVal) {
      if (newVal) {
        // Mobile-specific logic here
      } else {
        // Desktop-specific logic here
      }
    },
  },
  mounted() {
    window.addEventListener("resize", this.handleResize);
    this.handleResize();
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    closeWindow() {
      this.$emit("close");
    },
    postBuzz() {},
    setSelectedRate(rate) {
      console.log(`Selected Fee Rate: ${rate.value} sat/vB`);
    },
    handleResize() {
      this.isMobile = window.innerWidth <= 768;
    },
    async imageTxs() {
			let fileTransactions = []
			const finalAttachMetafileUri = []
			for (let i = 0; i < this.$refs.uploader.fileList.length; i++) {
				const current = this.$refs.uploader.fileList[i]

				// 压缩图片
				const compressed = await metaidv2Utils.compressImage(current.file)
				const fileResult = await metaidv2Utils.fileToAttachment(
					current.type === 'image/gif' ? current.file : compressed
				)
				let opReturnFieldList = [
					Buffer.from('metaid'),
					Buffer.from('create'),
					Buffer.from('/file'),
					Buffer.from('0'),
					Buffer.from('1.0.0'),
					Buffer.from(`${fileResult.fileType};binary`),
					Buffer.from(Buffer.from(fileResult.data, 'hex'))
				]
				//console.log('imageTxs', opReturnFieldList.toString())
				const { transactions } = await window.$walletUtils.createPin(
					opReturnFieldList,
					{
						serialAction: 'combo',
						transactions: fileTransactions
					}
				)
				if (!transactions) {
					throw new Error('upload image file failed')
				}
				finalAttachMetafileUri.push(
					'metafile://' +
						transactions[transactions.length - 1].txComposer.getTxId() +
						'i0'
				)
				fileTransactions = transactions
			}
			return {
				transactions: fileTransactions,
				attachments: finalAttachMetafileUri
			}
		},
    handleSubmit() {
      this.sureBtnLoading = true;
      const formName = "newBuzzForm";
      this.$refs[formName]
        .validateFields()
        .then(async (valid) => {
          if (valid) {
            let options = {
              content: this.form.content,
            };

            //图片添加add images
            const imageRes = await this.imageTxs();

            options.transactions = imageRes.transactions;
            options.attachments = imageRes.attachments;

            if (this.isPayForward) {
              options.quotePin = this.quotePin.id;
            }
            let res = null;
            if (this.isPayComment) {
              options.commentTo = this.quotePin.id;

              res = await window.$walletUtils
                .payComment(options)
                .catch((res) => {
                  this.sureBtnLoading = false;
                  this.$message.error("Error comment Buzz:" + res);
                });
            } else {
              console.log("handleSubmit *** options", options);
              res = await window.$walletUtils
                .shareToBuzz(options)
                .catch((res) => {
                  this.sureBtnLoading = false;
                  // this.$message.error("Error Buzz:" + res);
                  console.log("handleSubmit *** Error", res);
                });
              console.log("handleSubmit ***", res);
            }

            this.sureBtnLoading = false;
            this.$refs[formName].resetFields();
            if (res) {
              // 分享成功
              this.$emit("newBuzzSuccess");
              // this.$message.success(this.$t('csp_026'))
              this.visibleInChild = false;
            }
          } else {
            this.sureBtnLoading = false;
          }
        })
        .catch((error) => {
          this.sureBtnLoading = false;
        });
    },
  },
};
</script>

<template>
  <div>
    <div class="buzz-window" :class="{ 'is-mobile': isMobile }">
      <header class="buzz-header">
        <h1>New Post</h1>
        <i
          class="iconfont icon-guanbi"
          @click="closeWindow"
          style="font-size: 30px; cursor: pointer"
        ></i>
      </header>
      <Form class="buzz-form" :model="form" ref="newBuzzForm">
        <div>
          <FormItem
            name="content"
            class="enter-x"
            :rules="[{ required: true, message: 'Please input your Buzz!' }]"
          >
            <textarea
              id="buzzTextArea"
              placeholder="please input content"
              v-model="form.content"
              name="post"
              cols="30"
              rows="10"
            />
          </FormItem>
        </div>
        <div style="overflow: hidden">
          <label class="select-image" for="image-input">Select Image(s)</label>
        </div>
        <input id="image-input" type="file" multiple hidden />
        <section class="fee-rate-section" v-if="showFee">
          <div class="rate-left">
            <div class="title">Fee Rate:</div>
            <div class="rate-input-wrap">
              <input type="text" class="_input" />
              <span class="unit">sat/vB</span>
            </div>
          </div>
          <div class="rate-right">
            <div
              v-for="(rate, index) in feeRates"
              :key="index"
              class="rate-option"
            >
              <div class="value">
                {{ rate.name }}
              </div>
              <div class="label" :for="`rate-option-${index}`">
                {{ rate.value }} sat/vB
              </div>
            </div>
          </div>
        </section>
        <footer class="buzz-footer">
          <Button
            type="submit"
            :loading="sureBtnLoading"
            class="btn"
            @click="handleSubmit"
            >Post</Button
          >
        </footer>
      </Form>
    </div>
    <div class="model-wrap" @click="closeWindow"></div>
    <msgPost
      v-if="buzzDetail.id"
      isComment
      :pinInfo="buzzDetail"
      @showBuzzDetail="showBuzzDetail"
    ></msgPost>
  </div>
</template>

<style lang="less" scoped>
.buzz-window {
  position: fixed;
  top: 0;
  top: 50%;
  left: 0;
  left: 50%;
  z-index: 999;
  width: 600px;
  overflow: hidden;
  background-color: #fff;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  border-radius: 20px;
  // 页面居中
  transform: translate(-50%, -50%);
}

.buzz-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  color: #333;
  background-color: #fff;

  h1 {
    flex: 1;
    color: #00b1ff;
    text-align: center;
  }

  .btn-wrap {
    font-size: 26px;
    color: #333;
    background: transparent;
    border: none;
    outline: none;
  }
}

.buzz-form {
  width: 100%;
  padding: 12px;
  background-color: white;
  background-color: #fff;

  /* stylelint-disable-next-line selector-id-pattern */
  #buzzTextArea {
    width: 100%;
    height: 150px;
    padding: 10px;
    color: #333;
    background: #f2f2f2;
    border: none;
    border-radius: 12px;
    outline: none;
  }
}

.rate-option {
  display: flex;
  flex: 1;
  margin-right: 1rem;

  .value {
    margin-right: 20px;
    color: #fff;
  }

  .label {
    color: #00b1ff;
  }
}

.buzz-footer {
  display: flex;
  justify-content: center;
  padding: 10px 0 5px;

  .btn {
    width: 100%;
    color: #fff;
    background: #00b1ff;
    border: none;
    border-radius: 12px;
    outline: none;
  }
}

.is-mobile {
  width: 100%;
  height: 100%;
}

.is-mobile .buzz-form {
  padding: 0.5rem;
}

.fee-rate-section {
  display: flex;
  padding: 20px;
  margin-top: 10px;
  border: 1px solid #00b1ff;
  border-radius: 12px;

  .rate-left {
    flex: 1;

    .title {
      margin-bottom: 20px;
      font-size: 16px;
      color: #fff;
    }

    .rate-input-wrap {
      display: flex;
      align-items: center;

      ._input {
        width: 140px;
        padding: 10px;
        color: #00b1ff;
        border: 1px solid #00b1ff;
        border-radius: 12px;
      }

      .unit {
        margin-left: 10px;
        color: #00b1ff;
      }
    }
  }
}

.model-wrap {
  position: fixed;
  inset: 0;
  z-index: 998;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.7;
}

.select-image {
  display: block;
  float: right;
  padding: 5px;
  margin-top: 5px;
  font-size: 12px;
  line-height: 1;
  color: #333;
  border: 1px solid #333;
  border-radius: 10px;
}
</style>
